package config

type GeneratorConfigExists string

const (
	ExistsError     GeneratorConfigExists = "error"
	ExistsSkip      GeneratorConfigExists = "skip"
	ExistsOverwrite GeneratorConfigExists = "overwrite"
)

type Generator struct {
	Name     string    `hcl:",label" cty:"name"` //定义一个名字，用于模块覆盖使用
	Exclude  *[]string `hcl:"exclude,attr" cty:"exclude"`
	Include  *[]string `hcl:"include,attr" cty:"include"`
	Path     string    `hcl:"path,attr" cty:"path"`
	IfExists *string   `hcl:"if_exists" cty:"if_exists"`
	Content  Body      `hcl:"content,block" cty:"content"`

	GeneratedFiles map[string]bool
}

func (g *Generator) SetGeneratedFile(filename string) {
	if g.GeneratedFiles == nil {
		g.GeneratedFiles = make(map[string]bool)
	}
	g.GeneratedFiles[filename] = true
}

func (g *Generator) IsGenerated(filename string) bool {
	if g.GeneratedFiles == nil {
		return false
	}
	return g.GeneratedFiles[filename]
}

func (g *Generator) IsIfExists(exists GeneratorConfigExists) bool {
	ifExists := ExistsError
	if g.IfExists != nil {
		ifExists = GeneratorConfigExists(*g.IfExists)
	}
	return ifExists == exists
}

type Generators []*Generator

func (g Generators) indexOf(name string) int {
	for i, generator := range g {
		if generator.Name == name {
			return i
		}
	}
	return -1
}

func MergeGenerators(g1, g2 Generators) Generators {
	g := Generators{}
	for _, generator := range g1 {
		if idx := g.indexOf(generator.Name); idx != -1 {
			g[idx] = generator
		} else {
			g = append(g, generator)
		}
	}
	for _, generator := range g2 {
		if idx := g.indexOf(generator.Name); idx != -1 {
			g[idx] = generator
		} else {
			g = append(g, generator)
		}
	}
	return g
}
